<template>
  <div id="Login" @click="showLogin(false)">
    <div class="box-bg" @click.stop>
      <div class="content">       
        <el-tabs class="login-tab" v-model="tabActive">
          <el-tab-pane class="login-pane" label="登录" name="login">
            <p class="qq-weibo">
              <svg class="icon" aria-hidden="true" @click="socialLogin">
                <use xlink:href="#icon-QQ1"></use>
              </svg>
              <svg class="icon" aria-hidden="true" @click="socialLogin">
                <use xlink:href="#icon-weibo"></use>
              </svg>
            </p>
            <el-divider content-position="center">or</el-divider>
            <el-form :model="loginForm" :rules="rules" ref="loginForm">
              <el-form-item prop="user">
                <el-input
                  class="input-box"
                  placeholder="* 用户名或邮箱"
                  v-model="loginForm.user"
                  clearable
                  @keyup.enter="loginSubmitHandler"
                >
                </el-input>
              </el-form-item>
              <el-form-item prop="pw">
                <el-input
                  class="input-box"
                  placeholder="* 密码" 
                  v-model="loginForm.pw" 
                  show-password
                  @keyup.enter="loginSubmitHandler"
                >
                </el-input>
              </el-form-item>
            </el-form>
            <el-button 
              class="login-btn confirm-btn" 
              type="primary"
              @click="loginSubmitHandler"
            >
              立刻登录
            </el-button>
            <router-link :to="'/retrieve-pw'">
              <el-link>
                忘记密码？
              </el-link>
            </router-link>
          </el-tab-pane>
          <el-tab-pane class="reg-pane" label="注册" name="register">
            <p class="qq-weibo">
              <svg class="icon" aria-hidden="true" @click="socialLogin">
                <use xlink:href="#icon-QQ1"></use>
              </svg>
              <svg class="icon" aria-hidden="true" @click="socialLogin">
                <use xlink:href="#icon-weibo"></use>
              </svg>
            </p>
            <el-divider content-position="center">or</el-divider>
            <!-- 注册表单 -->
            <el-form :model="regForm" :rules="rules" ref="regForm">
              <el-form-item prop="user">
                <el-input
                  class="input-box"
                  placeholder="* 用户名"
                  v-model="regForm.user"
                  clearable
                  @keyup.enter="regSubmitHandler"
                >
                </el-input>
              </el-form-item>
              <el-form-item prop="email">
                <el-input
                  class="input-box"
                  placeholder="* 邮箱"
                  v-model="regForm.email"
                  clearable
                  @keyup.enter="regSubmitHandler"
                >
                </el-input>
              </el-form-item>
              <el-form-item prop="pw">
                <el-input
                  class="input-box"
                  placeholder="* 密码"
                  v-model="regForm.pw" 
                  show-password
                  @keyup.enter="regSubmitHandler"
                >
                </el-input>
              </el-form-item>
              <el-form-item prop="pw2">
                <el-input
                  class="input-box"
                  placeholder="* 确认密码"
                  v-model="regForm.pw2"
                  show-password
                  @keyup.enter="regSubmitHandler"
                >
                </el-input>
              </el-form-item>
              <el-form-item prop="verCode">
                <el-input
                  placeholder="* 邮箱验证码"
                  v-model="regForm.verCode"
                  class="input-with-select input-box"
                  @keyup.enter="regSubmitHandler"
                >
                  <template #append>
                    <el-button 
                      class="send-vercode-btn"
                      @click="getCode"
                      :loading="codeLoading"
                      :disabled="codeDisable"
                    >
                      {{ codeTip }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
            <el-button 
              class="reg-btn confirm-btn" 
              type="primary"
              @click="regSubmitHandler"
            >
              现在注册
            </el-button>
            <router-link :to="'/retrieve-pw'">
              <el-link>
                忘记密码？
              </el-link>
            </router-link>
          </el-tab-pane>
        </el-tabs>        
        <p></p>
      </div>      
    </div>
  </div>  
</template>

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  name: 'Login',
  data(){
    return{
      tabActive: 'login',
      codeLoading: false,
      codeTip: '发送验证码',
      intervalId: -1,
      codeDisable: false,
      loginForm:{
        user: '',
        pw: '',
      },
      regForm:{
        user: '',
        email: '',
        pw: '',
        pw2: '',
        verCode: ''
      },
      rules:{
        // 输入规则验证
        user: [{
          validator(rule, value, callback) {
            let reg = /^[^\s]{2,8}$/
            if (reg.test(value)) {
              callback()
            } else {
              callback(new Error("2-8位非空格字符"))
            }
          },
          trigger: 'blur'
        }],
        email: [{
          validator(rule, value, callback) {
            let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
            if (reg.test(value)) {
              callback()
            } else {
              callback(new Error("请输入正确的邮箱地址"))
            }
          },
          trigger: 'blur'
        }],
        pw: [{
          validator(rule, value, callback) {
            let reg = /^[\w,.?;<>/|\\:'"!@#$%^&*()+-]{6,16}$/
            if (reg.test(value)) {
              callback()
            } else {
              callback(new Error("6-16位字符"))
            }
          },
          trigger: 'blur'
        }],
        pw2: [{
          validator: (rule, value, callback) => {
            if (!value){
              callback(new Error("密码不能为空"))
            }else if (value !== this.regForm.pw) {
              callback(new Error("两次输入密码不一致"))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        verCode: [{
          validator: (rule, value, callback) => {
            let reg = /^\d{4}$/
            if (reg.test(value)){
              callback()
            } else {
              callback(new Error("验证码需为4位数字"))
            }
          },
          trigger: 'blur'
        }]
      }
    }
  },
  computed:{
    ...mapState(['isShowLoginBox'])
  },
  methods:{
    ...mapMutations(['showLogin', 'updateUserInfo']),
    socialLogin(){
      this.$message('暂未开通，敬请等待...')
    },
    // 发送验证码
    async getCode(){
      let userReg = /^[^\s]{2,8}$/
      let regEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      let email = this.regForm.email.trim()
      let user = this.regForm.user.trim()
      if(user === ''){
        return this.$message.error('请先填写用户名')
      }
      if(!userReg.test(user)){
        return this.$message.error('用户名为2-8位非空格字符')
      }
      if(email === ''){
        return this.$message.error('请先填写邮箱')
      }
      if(!regEmail.test(email)){
        return this.$message.error('邮箱格式不正确')
      }
      this.codeLoading = true
      let {data} = await this.$axios({
        method: 'post',
        url: '/email/getcode',
        data: {
          user,
          email
        }
      })

      this.codeLoading = false
      if(data.code){
        return this.$message.error(data.msg)
      }

      this.codeCooling()
    },
    // 验证码请求冷却时间
    codeCooling(){
      let time = 60
      this.codeDisable = true
      this.intervalId = setInterval(()=>{
        time--
        this.codeTip = `发送验证码 (${time})`
        if(time === 0){
          this.codeTip = '发送验证码'
          this.codeDisable = false
          clearInterval(this.intervalId)
        }
      },1000)
    },
    // 注册提交
    regSubmitHandler(){
      this.$refs.regForm.validate(async valid => {
        if(valid){
          // 注册请求
          let user = this.regForm.user.trim()
          let pass = this.regForm.pw.trim()
          let email = this.regForm.email.trim()
          let code = this.regForm.verCode.trim()
          let {data} = await this.$axios({
            method: 'post',
            url: "/reg",
            data:{
              user,pass,email,code
            }
          })

          if(data.code){
            // 注册失败提示
            return this.$message.error(data.msg)
          }

          // --- 注册成功 --- //
          // 清空注册表单输入
          this.$refs.regForm.resetFields()
          // 注册成功提示
          this.$message.success('注册成功')
          // 跳转至登录tab
          this.tabActive = 'login'
        }else{
          return false
        }
      })
    },
    // 登录提交
    loginSubmitHandler(){
      this.$refs.loginForm.validate(async valid => {
        if(valid){
          // 登录请求
          let user = this.loginForm.user.trim()
          let pass = this.loginForm.pw.trim()
          let {data} = await this.$axios({
            method: 'post',
            url: "/login",
            data:{
              user, pass
            }
          })

          if(data.code){
            // 登录失败提示
            return this.$message.error(data.msg)
          }
          // --- 登录成功 --- //
          // 清空注册表单输入
          this.$refs.loginForm.resetFields()
          // 登录成功提示
          this.$message.success('登录成功')
          // 关闭登录注册框
          this.showLogin(false)
          // 修改vuex
          this.updateUserInfo(data.data)
        }else{
          return false
        }
      })
    }
  },
  updated(){
    this.$refs.loginForm.resetFields()
    this.$refs.regForm.resetFields()
  }
}
</script>

<style lang="less" scoped>
@boxWidth: 340px;
@contentWidth:270px;

#Login{
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  display: table;
  background-color: rgba(0, 0, 0, .3);
  backdrop-filter: blur(3px);
  z-index: 2;

  .box-bg{
    position: absolute;
    width: @boxWidth;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(1);
    transition: transform .2s;
    background-color: #fff;
    border-radius: 8px;
    .content{
      width: @contentWidth;
      margin: 0 auto;
      padding: 20px 0;
      .login-tab{
        .login-pane, .reg-pane{
          .qq-weibo{
            margin-bottom: 20px;
            .icon{
              width: 2.2em;
              height: 2.2em;
              padding: 0 16px;
              cursor: pointer;
            }
          }
          .input-box{
            // margin: 0 0 25px;
          }
          .confirm-btn{
            width: @contentWidth;
            margin-bottom: 20px;
          }
        }
      }
    }
  }

  /deep/ .el-tabs__active-bar, /deep/ .el-tabs__nav-wrap::after{
    height: 0;
  }

  /deep/ .el-tabs__nav{      
    left:31%
  }

  /deep/ .el-tabs__item.is-active, /deep/ .el-tabs__item:hover{
    color: #007fff;
  }

  /deep/ .el-tabs__item{
    font-size: 15px;
    font-weight: bold;
    color: rgba(0,127,255,.4);
  }

  /deep/ .el-divider__text{
    color: #545454;
    font-size: 18px;
    font-weight: normal;
  }

  /deep/ .el-input-group__append, .el-input-group__prepend{
    color: #ffffff;    
    background: #20a0ff;
    background: -webkit-gradient(linear,left top,right top,from(#20a0ff),to(#20b8ff));
    background: -webkit-linear-gradient(left,#20a0ff,#20b8ff);
    background: linear-gradient(90deg,#20a0ff,#20b8ff);
    -webkit-box-shadow: 0 3px 5px rgb(32 160 255 / 50%);
    box-shadow: 0 3px 5px rgb(32 160 255 / 50%);
  }

  /deep/ .el-button--primary{
    color: #ffffff;
    font-weight: bold;
    background: #34495e;
    background: -webkit-gradient(linear,left top,right top,from(#34495e),to(#475f77));
    background: -webkit-linear-gradient(left,#34495e,#475f77);
    background: linear-gradient(90deg,#34495e,#475f77);
    -webkit-box-shadow: 0 3px 5px rgba(52, 73, 94, .5);
    box-shadow: 0 3px 5px rgba(52, 73, 94, .5);
    border-color: transparent;
    box-shadow: none;
  }

  .send-vercode-btn{
    font-weight: bold;
    background: #20a0ff;
    background: -webkit-gradient(linear,left top,right top,from(#20a0ff),to(#20b8ff));
    background: -webkit-linear-gradient(left,#20a0ff,#20b8ff);
    background: linear-gradient(90deg,#20a0ff,#20b8ff);
    -webkit-box-shadow: 0 2px 6px rgba(32, 160, 255, .4);
    box-shadow: 0 2px 6px rgba(32, 160, 255, .4);    
  }
}
</style>